package demo.reflect;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author zhanghaixuan
 * @date 2020-03-05 11:12
 */
@Slf4j
public class FieldCollector {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<?> clazz = Class.forName("demo.reflect.ReflectTarget");

        /**
         * 获取所有公有的字段
         */
        Field[] fields = clazz.getFields();

        for (Field field : fields) {
            log.info("公有的字段有:{}",field);
        }

        /**
         * 获取所有的字段
         */
        Field[] declaredFields = clazz.getDeclaredFields();

        for (Field declaredField : declaredFields) {
            log.info("所有的字段:{}",declaredField);
        }

        /**
         * 获取某个字段
         */

        Field name = clazz.getField("name");
        log.info("所有的特定的字段:{}",name);

        final Constructor<?> constructor = clazz.getConstructor();
        constructor.setAccessible(true);
        final ReflectTarget reflectTarget = (ReflectTarget) constructor.newInstance();
        name.set(reflectTarget,"test");
        log.info("验证赋值操作:name={}",reflectTarget.name);

        final Field targetInfo = clazz.getDeclaredField("targetInfo");
        targetInfo.setAccessible(true);
        targetInfo.set(reflectTarget,"targetInfo");
        log.info("验证赋值操作:targetInfo={}",reflectTarget.toString());


    }
}
